package com.richstonedt.smartcity.xaytsccommoncs.aspect;

import com.obs.services.ObsClient;
import com.richstonedt.smartcity.xaytsccommoncs.config.ObsProperties;
import com.richstonedt.smartcity.xaytsccommoncs.util.ObsUtil;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <b><code>ObsAspect</code></b>
 * <p/>
 * Description  obs工具切面类（为了创建和关闭obsClient）
 * <p/>
 * <b>Creation Time:</b> 2022/3/29 15:56:45
 *
 * @author tangjiahuan
 * @since xaytsc-common-be
 */
@Component
@Aspect
public class ObsAspect {
    private final static Logger logger = LoggerFactory.getLogger(ObsAspect.class);

    private final ObsProperties obsProperties;
    private final ObsUtil obsUtil;

    public ObsAspect(ObsProperties obsProperties, ObsUtil obsUtil) {
        this.obsProperties = obsProperties;
        this.obsUtil = obsUtil;
    }

    /**
     * 定义切入点，前置和后置表达式都一样的所以定义在这里
     * 通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut("@annotation(com.richstonedt.smartcity.xaytsccommoncs.annotation.ObsClientAnnotation)")
    public void obsPointcut() {
    }

    @Before("obsPointcut()")
    public void init() {
        //创建客户端连接
        ObsClient obsClient = new ObsClient(obsProperties.getAk(), obsProperties.getSk(), obsUtil.getConfig());
        obsUtil.setObsClient(obsClient);
        logger.info("======obsService init========");
    }

    @After("obsPointcut()")
    public void closeClient() {
        //关闭客户端连接
        if (obsUtil.getObsClient() != null) {
            try {
                obsUtil.getObsClient().close();
                logger.info("======closeClient========");
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("[ "+this.getClass()+" - 关闭obs客户端连接失败 ]");
            }
        }
    }

}
